package handlers

import (
	"database/sql"
	"net/http"
	"strconv"

	"saysay/models"
	"saysay/utils"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

var (
	db         *sql.DB
	wordFilter *utils.SensitiveWordFilter
)

// InitHandlers 初始化处理器
func InitHandlers(database *sql.DB) {
	db = database
	wordFilter = utils.NewSensitiveWordFilter()
}

// ========== 用户相关处理器 ==========

// RegisterPageHandler 注册页
func RegisterPageHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "register.html", gin.H{
		"title": "用户注册",
	})
}

// RegisterHandler 用户注册
func RegisterHandler(c *gin.Context) {
	username := c.PostForm("username")
	nickname := c.PostForm("nickname")
	password := c.PostForm("password")

	// 验证输入
	if username == "" || nickname == "" || password == "" {
		c.HTML(http.StatusBadRequest, "register.html", gin.H{
			"error": "所有字段不能为空",
			"title": "用户注册",
		})
		return
	}

	// 用户名长度限制
	if len(username) > 32 {
		c.HTML(http.StatusBadRequest, "register.html", gin.H{
			"error": "用户名长度不能超过32个字符",
			"title": "用户注册",
		})
		return
	}

	// 检查用户名是否存在
	exists, err := models.CheckUsernameExists(db, username)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "register.html", gin.H{
			"error": "系统错误",
			"title": "用户注册",
		})
		return
	}

	if exists {
		c.HTML(http.StatusBadRequest, "register.html", gin.H{
			"error": "用户名已存在",
			"title": "用户注册",
		})
		return
	}

	// 创建用户
	err = models.CreateUser(db, username, nickname, password)
	if err != nil {
		utils.Error("用户注册失败: %v, 用户名: %s", err, username)
		c.HTML(http.StatusInternalServerError, "register.html", gin.H{
			"error": "注册失败，请重试",
			"title": "用户注册",
		})
		return
	}

	utils.Info("用户注册成功: %s", username)
	c.HTML(http.StatusOK, "register_success.html", gin.H{
		"title":   "注册成功",
		"message": "注册成功，请登录",
	})
}

// LoginPageHandler 登录页
func LoginPageHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{
		"title": "用户登录",
	})
}

// LoginHandler 用户登录
func LoginHandler(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.HTML(http.StatusBadRequest, "login.html", gin.H{
			"error": "用户名和密码不能为空",
			"title": "用户登录",
		})
		return
	}

	user, err := models.CheckUser(db, username, password)
	if err != nil {
		utils.Debug("用户登录失败: %v, 用户名: %s", err, username)
		c.HTML(http.StatusUnauthorized, "login.html", gin.H{
			"error": "用户名或密码错误",
			"title": "用户登录",
		})
		return
	}

	utils.Info("用户登录成功: %s (ID: %d)", user.Username, user.ID)

	// 创建会话
	session := sessions.Default(c)
	session.Set("user_id", user.ID)
	session.Set("username", user.Username)
	session.Set("nickname", user.Nickname)
	err = session.Save()
	if err != nil {
		utils.Error("保存Session失败: %v", err)
		c.HTML(http.StatusInternalServerError, "login.html", gin.H{
			"error": "系统错误，请稍后重试",
			"title": "用户登录",
		})
		return
	}

	utils.Info("Session保存成功，重定向到首页")
	c.Redirect(302, "/")
}

// LogoutHandler 用户登出
func LogoutHandler(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	session.Save()

	c.Redirect(302, "/")
}

// ========== 首页和处理 ==========

// IndexHandler 首页处理器
func IndexHandler(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			utils.Error("IndexHandler panic: %v", r)
			panic(r) // 重新抛出让recoveryMiddleware处理
		}
	}()

	utils.Debug("IndexHandler called")

	// 获取分页参数
	page := 1
	pageStr := c.Query("page")
	if pageStr != "" {
		var err error
		page, err = strconv.Atoi(pageStr)
		if err != nil || page < 1 {
			page = 1
		}
	}

	pageSize := 20
	offset := (page - 1) * pageSize

	utils.Debug("Fetching shuoshuos: offset=%d, limit=%d", offset, pageSize)

	// 获取说说列表
	shuoshuos, err := models.GetNormalShuoshuosWithUserPaged(db, offset, pageSize)
	if err != nil {
		utils.Error("GetNormalShuoshuosWithUserPaged failed: %v", err)
		c.HTML(http.StatusInternalServerError, "index.html", gin.H{
			"error": "获取说说失败",
		})
		return
	}

	utils.Debug("Got %d shuoshuos", len(shuoshuos))

	// 获取总数
	total, err := models.GetTotalShuoshuosCount(db)
	if err != nil {
		total = 0
	}

	// 计算总页数
	totalPages := (total + pageSize - 1) / pageSize
	if totalPages == 0 {
		totalPages = 1
	}

	// 获取当前用户信息
	session := sessions.Default(c)
	userID := session.Get("user_id")
	var currentUserID int
	var currentNickname string
	utils.Debug("Session user_id: %v (type: %T)", userID, userID)

	if userID != nil {
		var ok bool
		currentUserID, ok = userID.(int)
		if !ok {
			utils.Error("user_id type assertion failed: %v (type: %T)", userID, userID)
		}
		if nickname := session.Get("nickname"); nickname != nil {
			currentNickname = nickname.(string)
		}
		utils.Debug("Current user: ID=%d, Nickname=%s", currentUserID, currentNickname)
	} else {
		utils.Debug("No user session found")
	}

	// 计算上一页和下一页
	prevPage := page - 1
	if prevPage < 1 {
		prevPage = 1
	}
	nextPage := page + 1
	if nextPage > totalPages {
		nextPage = totalPages
	}

	utils.Debug("Rendering template with data: page=%d, total=%d, shuoshuos=%d, is_logged_in=%v",
		page, total, len(shuoshuos), userID != nil)

	utils.Debug("About to call c.HTML")
	c.HTML(http.StatusOK, "index.html", gin.H{
		"shuoshuos":        shuoshuos,
		"title":            "匿名树洞",
		"is_logged_in":     userID != nil,
		"current_user_id":  currentUserID,
		"current_nickname": currentNickname,
		"page":             page,
		"total":            total,
		"total_pages":      totalPages,
		"page_size":        pageSize,
		"prev_page":        prevPage,
		"next_page":        nextPage,
	})
	utils.Debug("Template rendered successfully")
}

// PostShuoshuoHandler 发布说说处理器
func PostShuoshuoHandler(c *gin.Context) {
	// 检查登录状态
	session := sessions.Default(c)
	userID := session.Get("user_id")
	if userID == nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "请先登录",
		})
		return
	}

	// 检查用户是否被拉黑（静默处理，不向用户透露）
	user, err := models.GetUserByID(db, userID.(int))
	if err == nil && user.IsBanned {
		c.JSON(http.StatusForbidden, gin.H{
			"error": "操作失败，请稍后重试",
		})
		return
	}

	content := c.PostForm("content")

	if content == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "内容不能为空",
		})
		return
	}

	// XSS过滤
	content = utils.FilterXSS(content)

	// 敏感词检测
	hasSensitive, msg := wordFilter.CheckContent(content)
	if hasSensitive {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": msg,
		})
		return
	}

	// 保存到数据库
	err = models.CreateShuoshuoWithUser(db, userID.(int), content)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "发布失败，请稍后重试",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "发布成功",
	})
}

// DeleteShuoshuoHandler 删除说说
func DeleteShuoshuoHandler(c *gin.Context) {
	// 检查登录状态
	session := sessions.Default(c)
	userID := session.Get("user_id")
	if userID == nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "请先登录",
		})
		return
	}

	idStr := c.PostForm("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "无效的ID",
		})
		return
	}

	err = models.DeleteShuoshuo(db, id, userID.(int))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "删除失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "删除成功",
	})
}

// PostCommentHandler 发表评论
func PostCommentHandler(c *gin.Context) {
	// 检查登录状态
	session := sessions.Default(c)
	userID := session.Get("user_id")
	if userID == nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "请先登录",
		})
		return
	}

	// 检查用户是否被拉黑（静默处理）
	user, err := models.GetUserByID(db, userID.(int))
	if err == nil && user.IsBanned {
		c.JSON(http.StatusForbidden, gin.H{
			"error": "操作失败，请稍后重试",
		})
		return
	}

	shuoshuoIDStr := c.PostForm("shuoshuo_id")
	content := c.PostForm("content")

	shuoshuoID, err2 := strconv.Atoi(shuoshuoIDStr)
	if err2 != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "无效的说说ID",
		})
		return
	}

	if content == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "评论内容不能为空",
		})
		return
	}

	// 敏感词检测
	hasSensitive, msg := wordFilter.CheckContent(content)
	if hasSensitive {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": msg,
		})
		return
	}

	// 保存评论
	err = models.CreateComment(db, shuoshuoID, userID.(int), content)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "发表评论失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "评论成功",
	})
}

// GetCommentsHandler 获取评论（支持分页）
func GetCommentsHandler(c *gin.Context) {
	shuoshuoIDStr := c.Query("shuoshuo_id")
	pageStr := c.Query("page")

	shuoshuoID, err := strconv.Atoi(shuoshuoIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "无效的说说ID",
		})
		return
	}

	// 默认显示第1页（1条评论）
	page := 1
	if pageStr != "" {
		page, err = strconv.Atoi(pageStr)
		if err != nil || page < 1 {
			page = 1
		}
	}

	// 第1页显示1条，后续每页显示10条
	limit := 1
	offset := 0
	if page > 1 {
		limit = 10
		offset = 1 + (page-2)*10
	}

	comments, err := models.GetCommentsByShuoshuoIDPaged(db, shuoshuoID, offset, limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "获取评论失败",
		})
		return
	}

	// 获取评论总数
	total, err := models.GetCommentCount(db, shuoshuoID)
	if err != nil {
		total = 0
	}

	// 计算是否还有更多
	hasMore := offset+limit < total

	c.JSON(http.StatusOK, gin.H{
		"comments": comments,
		"total":    total,
		"has_more": hasMore,
	})
}

// ========== 管理员相关处理器（保持不变）==========

// AdminLoginPageHandler 管理员登录页
func AdminLoginPageHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "admin_login.html", gin.H{
		"title": "管理员登录",
	})
}

// AdminLoginHandler 管理员登录处理器
func AdminLoginHandler(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.HTML(http.StatusBadRequest, "admin_login.html", gin.H{
			"error": "用户名和密码不能为空",
			"title": "管理员登录",
		})
		return
	}

	ok, err := models.CheckAdmin(db, username, password)
	if err != nil || !ok {
		c.HTML(http.StatusUnauthorized, "admin_login.html", gin.H{
			"error": "用户名或密码错误",
			"title": "管理员登录",
		})
		return
	}

	// 创建会话
	session := sessions.Default(c)
	session.Set("admin_id", username)
	session.Set("admin_username", username)
	session.Save()

	c.Redirect(302, "/admin")
}

// AdminHandler 管理后台页面
func AdminHandler(c *gin.Context) {
	shuoshuos, err := models.GetAllShuoshuosWithUser(db)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "admin.html", gin.H{
			"error": "获取说说失败",
			"title": "管理后台",
		})
		return
	}

	c.HTML(http.StatusOK, "admin.html", gin.H{
		"shuoshuos": shuoshuos,
		"title":     "管理后台",
	})
}

// ToggleViolationHandler 切换违规状态
func ToggleViolationHandler(c *gin.Context) {
	var req struct {
		ID int `json:"id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "参数错误",
		})
		return
	}

	err := models.ToggleViolation(db, req.ID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "操作失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "操作成功",
	})
}

// AdminLogoutHandler 退出登录
func AdminLogoutHandler(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	session.Save()

	c.Redirect(302, "/admin/login")
}

// AdminUsersHandler 用户管理页面
func AdminUsersHandler(c *gin.Context) {
	users, err := models.GetAllUsers(db)
	if err != nil {
		utils.Error("获取用户列表失败: %v", err)
		c.HTML(http.StatusInternalServerError, "admin_users.html", gin.H{
			"error": "获取用户列表失败",
			"title": "用户管理",
		})
		return
	}

	utils.Debug("加载用户管理页面，用户数量: %d", len(users))
	for i, u := range users {
		utils.Debug("用户 %d: ID=%d, Username=%s, Nickname=%s, IsBanned=%v",
			i, u.ID, u.Username, u.Nickname, u.IsBanned)
	}

	c.HTML(http.StatusOK, "admin_users.html", gin.H{
		"users": users,
		"title": "用户管理",
	})
}

// AdminBanUserHandler 拉黑/取消拉黑用户
func AdminBanUserHandler(c *gin.Context) {
	var req struct {
		UserID int `json:"user_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "参数错误",
		})
		return
	}

	err := models.BanUser(db, req.UserID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "操作失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "操作成功",
	})
}

// AdminDeleteUserHandler 删除用户
func AdminDeleteUserHandler(c *gin.Context) {
	var req struct {
		UserID int `json:"user_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "参数错误",
		})
		return
	}

	err := models.DeleteUser(db, req.UserID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "删除失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "删除成功",
	})
}

// AdminDeleteShuoshuoHandler 管理员删除说说
func AdminDeleteShuoshuoHandler(c *gin.Context) {
	var req struct {
		ID int `json:"id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "参数错误",
		})
		return
	}

	err := models.AdminDeleteShuoshuo(db, req.ID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "删除失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "删除成功",
	})
}
